package com.xb.controller;

import com.xb.service.IUserService;
import com.xb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

/**
 * @author xbyan
 * @date 2023/7/9 19:02
 */
@Controller
public class EmailController {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IUserService userService;

    @PostMapping("/sendEmail")
    @ResponseBody
    public Result sendEmail(String email) {
        Result result = new Result();
        if (userService.selectUserByEmail(email) != null) {
            result.setMessage("此邮箱已被注册！");
            result.setStatus(Result.RESPONSE_FAIL);
            return result;
        }
        try {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            Long expire = redisTemplate.getExpire(email, TimeUnit.SECONDS);

            if (expire > 180) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("您在两分钟之内已申请过验证码了，请等待一会吧！");
                return result;
            }
            // 创建MimeMessage对象
            MimeMessage message = mailSender.createMimeMessage();

            // 使用MimeMessageHelper来设置邮件内容
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置发件人
            helper.setFrom("693094507@qq.com", "YBB");

            // 设置收件人
            helper.setTo(email);

            // 设置主题
            helper.setSubject("验证邮箱");

            // 读取HTML文件内容
            Path htmlFile = Paths.get("src", "main", "webapp", "WEB-INF", "email.html");
            String htmlContent = new String(Files.readAllBytes(htmlFile));

            // 生成随机验证码
            String verificationCode = generateRandomCode();

            // 将随机验证码插入到HTML文件中
            String htmlWithCode = htmlContent.replace("{code}", verificationCode);

            // 设置HTML内容
            helper.setText(htmlWithCode, true);

            valueOperations.set(email, verificationCode, 300, TimeUnit.SECONDS);

            // 发送邮件
            mailSender.send(message);

            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("验证码发送成功");
        } catch (MessagingException e) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("验证码发送失败，请稍后重试");
        } catch (Exception e) {
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("验证码发送失败！请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>");
            e.printStackTrace();
        }

        return result;
    }

    @PostMapping("/sendEmailToDel")
    @ResponseBody
    public Result sendEmailToDel(String email) {
        Result result = new Result();
        if (!("2278626932@qq.com").equals(email)) {
            result.setMessage("此邮箱不是超级管理员邮箱！");
            result.setStatus(Result.RESPONSE_FAIL);
            return result;
        }
        try {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            Long expire = redisTemplate.getExpire(email, TimeUnit.SECONDS);
            if (expire > 180) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("您在两分钟之内已申请过验证码了，请等待一会吧！");
                return result;
            }
            // 创建MimeMessage对象
            MimeMessage message = mailSender.createMimeMessage();

            // 使用MimeMessageHelper来设置邮件内容
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置发件人
            helper.setFrom("693094507@qq.com", "YBB");

            // 设置收件人
            helper.setTo(email);

            // 设置主题
            helper.setSubject("验证邮箱");

            // 读取HTML文件内容
            Path htmlFile = Paths.get("src", "main", "webapp", "WEB-INF", "email.html");
            String htmlContent = new String(Files.readAllBytes(htmlFile));

            // 生成随机验证码
            String verificationCode = generateRandomCode();

            // 将随机验证码插入到HTML文件中
            String htmlWithCode = htmlContent.replace("{code}", verificationCode);

            // 设置HTML内容
            helper.setText(htmlWithCode, true);

            valueOperations.set(email, verificationCode, 300, TimeUnit.SECONDS);

            // 发送邮件
            mailSender.send(message);

            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("验证码发送成功");
        } catch (MessagingException e) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("验证码发送失败，请稍后重试");
        } catch (Exception e) {
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("验证码发送失败！请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>");
            e.printStackTrace();
        }

        return result;
    }

    @PostMapping("/verifyCode")
    @ResponseBody
    public Result verifyCode(String code,String email){
        Result result = new Result();
        String verifyCode = "";
        try {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            verifyCode = valueOperations.get(email);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("出错了！请联系管理员 <a href=\"mailto:xb.yang1@outlook.com\">点击这里发送邮件给xb.yang1@outlook.com</a>");
            return result;
        }
        if(verifyCode.equals(code)){
            result.setStatus(Result.RESPONSE_SUCCESS);
        }else{
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("验证码错误");
        }
        return result;
    }

    private static String generateRandomCode() {
        // 生成随机验证码的逻辑
        // 这里使用一个简单的示例逻辑，生成一个4位数字验证码
        int code = (int) (Math.random() * 9000) + 1000;
        return String.valueOf(code);
    }

}
